﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;
using VDataAdapter.Communication;
using VDataAdapter.QueueManagement;
using VDataAdapter.EventManagement;

using PriceLibrary.PriceService;



namespace VDataAdapter.WorkerManagement
{
    class MarketInfoWorkerException : Exception
    {
        public MarketInfoWorkerException() : base() { }
        public MarketInfoWorkerException(string msg) : base(msg) { }
        public MarketInfoWorkerException(string msg, Exception inner) : base(msg, inner) { }
    }

    class MarketInfoWorker : Worker
    {
        private VDataCommunicator _sender;

        private IEventProviderQueue _eQueue;

        private EventQueueChecker _queueChecker;

        /// <summary>
        /// By deafult, MarketInfoWoker is Hard Working
        /// </summary>
        /// <param name="waitFirstTime"></param>
        /// <param name="sender"></param>
        /// <param name="eQueue"></param>
        public MarketInfoWorker(string parentName,ManualResetEvent waitFirstTime, VDataCommunicator sender, IEventProviderQueue eQueue) : base(waitFirstTime, null, true)
        {
            _sender = sender;
            _eQueue = eQueue;
            _name = parentName+"-MarketInfoWorker";
            _queueChecker = new EventQueueChecker(eQueue);
        }
 

        public bool StopCheckingQueue
        {
            get { return _queueChecker.StopCheckingQueue; }
            set { _queueChecker.StopCheckingQueue = value; }
        }

        override
        public void StopWork()
        {
            StopCheckingQueue = true;
        }

        protected override void DoWork(object data)
        {
            MarketInfosEvent e = (MarketInfosEvent)_queueChecker.CheckingQueue(EventType.MarketInfo);

            // do nothing because StopCheckingQueue is set
            if (e == null)
            {                
                return;
            }
            try
            {
                foreach (KeyValuePair<int, MarketInfo> p in e.MarketInfosList)
                {
                    _sender.SendMarketInfo(p.Key, p.Value);
                }
            }
            catch (Exception ex)
            {
                _status = "Exception in send marketinfo data";
                throw new MarketInfoWorkerException("Can not send marketinfo data: " + ex.Message, ex);
            }

        }

    }
}
